
import 'dart:collection';

import 'package:DiamondDiary/database/db_helper.dart';
import 'package:DiamondDiary/database/note_info.dart';
import 'package:DiamondDiary/database/tag_info.dart';
import 'package:DiamondDiary/pages/tag_page.dart';
import 'package:DiamondDiary/utils/route_helper.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

class NoteEditPage extends StatefulWidget{

  @override
  State<StatefulWidget> createState() {
    return NoteEditState();
  }

}

class NoteEditState extends State<NoteEditPage>{

  TextEditingController titleCtr, contentCtr;
  var noteInfo = NoteInfo(createTime: DateTime.now().millisecondsSinceEpoch );
  var tagList = <Map<String,dynamic>>[];
  var checkedTag = Set<String>();

  @override
  void initState() {
    titleCtr = TextEditingController();
    contentCtr = TextEditingController();
    super.initState();
    Future.delayed(Duration(milliseconds: 100),()async{
      var tags =await DBHelper().getTagInfo(limit: 10);
      if(tags!=null && tags.length>0){
        setState(() {
          tagList.addAll(tags);
        });
      }
    });
  }

  @override
  void dispose() {
    titleCtr.dispose();
    contentCtr.dispose();
    super.dispose();
  }

  void saveData(){
    if(titleCtr.text.isNotEmpty && contentCtr.text.isNotEmpty) {
      noteInfo.commitTime = DateTime.now().millisecondsSinceEpoch;
      noteInfo.targetTime = noteInfo.createTime;
      //targetTime
      noteInfo.title = titleCtr.text;
      noteInfo.content = contentCtr.text;
      noteInfo.tags = IterableBase.iterableToShortString(checkedTag,'','');
      DBHelper().saveNote(noteInfo);
      print("data saved");
      RouteHelper.pop(context);
    }
  }

  @override
  Widget build(BuildContext context) {
    return
      Scaffold(
        appBar: AppBar(title: Center(child:Text('编辑'),),actions: [
          InkWell(
            child:Padding(
              padding: EdgeInsets.only(left:10,right: 10),
              child: Center(child:Text('保存')),
            ),
            onTap: saveData,),
        ],),
        body: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Container(
              margin: EdgeInsets.all(15),
              padding: EdgeInsets.only(left: 10,right: 10),
              decoration: ShapeDecoration(
                color:Colors.white,
                shape:RoundedRectangleBorder(borderRadius:BorderRadius.all(Radius.circular(5))),
              ),
              child:TextField(
                controller: titleCtr,
                style: Theme.of(context)
                    .textTheme
                    .headline6
                    .copyWith(color: Colors.black87),
                autofocus: true,
                textInputAction: TextInputAction.next,
                decoration: InputDecoration(
                  border: InputBorder.none,
                  hintText: '标题',
                ),
              ),
            ),
            Expanded(
              child: Container(
                margin: EdgeInsets.fromLTRB(15, 0, 15, 15),
                padding: EdgeInsets.only(left: 10,right: 10),
                decoration:ShapeDecoration(
                  color:Colors.white,
                  shape:RoundedRectangleBorder(borderRadius:BorderRadius.all(Radius.circular(5))),
                ),
                child:TextField(
                  controller: contentCtr,
                  maxLines: null,
                  minLines: 2,
                  style:TextStyle(fontSize: 16,height: 1.6),
                  keyboardType: TextInputType.multiline,
                  textInputAction: TextInputAction.newline,
                  focusNode: FocusNode(),
                  decoration: InputDecoration(
                      border: InputBorder.none,
                      hintText: '内容',
                  ),
                ),
              ),
            ),
            Padding(
              padding: EdgeInsets.fromLTRB(15,0,15,10),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text('Tag'),
                  InkWell(child:Text('all'),
                    onTap: () => RouteHelper.routeTo(context, TagPage()).then((value){
                      if(value is List<Map<String,dynamic>>){
                        setState(() {
                          tagList.addAll(value);
                        });
                      }
                    }),
                  ),
                ],
              ),
            ),
            tagList.length>0?buildTags():SizedBox(height: 1,),
            SizedBox(height: 10,),
          ],
        ),
      );
  }

  Widget buildTags(){
    return Container(
      height: 30,
      child:ListView.separated(
        scrollDirection : Axis.horizontal,
        shrinkWrap: true,
        padding: EdgeInsets.only(left: 10,right: 10),
        itemBuilder: (context,index){
          var item = tagList[index];
          String tag = item['tag'];
          print(tag);
          return InkWell(
            onTap: (){
              if(checkedTag.contains(tag)) checkedTag.remove(tag);
              else checkedTag.add(tag);
              setState(() {

              });
            },
            child:Container(
              alignment: Alignment.center,
              padding: EdgeInsets.fromLTRB(8, 4, 8, 4),
              decoration:ShapeDecoration(
                color: checkedTag.contains(tag)? Colors.yellowAccent : Colors.black26,
                shape:RoundedRectangleBorder(borderRadius:BorderRadius.all(Radius.circular(5))),
              ) ,
              child: Text(tag?.toString()??'null'),
            ),
          );
        },
        separatorBuilder: (context,index)=>SizedBox(width: 10,),
        itemCount: tagList.length),
    );
  }

}